home *** CD-ROM | disk | FTP | other *** search
- Path: news.mira.net.au!news
- From: davidw@werple.net.au (David White)
- Newsgroups: comp.lang.c++
- Subject: Re: polymorphism and style
- Date: 26 Feb 1996 20:46:45 +1100
- Organization: Werple Internet, Melbourne
- Message-ID: <4grvi5$fs@werple.net.au>
- References: <4gr4ur$n13@alpha.pcix.com>
- NNTP-Posting-Host: werple.mira.net.au
-
- ed lizewski <elizewsk@capecod.net> writes:
-
- > Question on polymorphism and style.
- >Want to call a function in a most derived class off a pointer to the base
- >class. The fuction does not exist in the base class.
- >I should:
- >1)downcast ?
-
- This is one option. If your compiler has Run Time Type Information, one
- of the more recent additions to C++, you can safely use 'dynamic_cast'.
- Example:
- void f(Base *pb)
- {
- if(Derived *pd = dynamic_cast<Derived*>(pb))
- {
- //Use 'pd'
- }
- else
- {
- //'pb' is not a Derived*
- }
- }
- Without RTTI, you can use a traditional cast, but you have to know that
- it is a Derived*.
-
- >2)add the function to the base class and add virtual stubs to every
- > class that does not use it ?
-
- You shouldn't need to touch derived classes that have no interest in it.
-
- >3)add it to the base class but define it like
- > foo( ..whatever..) {error_msg("virtual function not defined");}
- > This way only the class that uses it would have to define it.
-
- Normally, you would only put a function in the base class if it makes
- sense for it, i.e., ask yourself if this is a function you could
- reasonably expect any derived class to implement sensibly. If the answer
- is no, it probably shouldn't be in the base class. Also, if you plan to
- use it in only one derived class, you'll have to know that a pointer is of
- that class when you call the function to avoid the error message, and if
- you know what class it is you don't need the function in the base class;
- you can just cast the pointer (although the base class function may be
- useful in debugging).
-
- In the absence of RTTI, you could make an exception to simulate
- 'dynamic_cast'. Example:
- class Circle;
- class Square;
-
- class Shape
- {
- //...
- virtual Circle *asCircle() { return 0; }
- virtual Square *asSquare() { return 0; }
- };
-
- class Circle : public Shape
- {
- //...
- Circle *asCircle() { return this; }
- };
- You can guess what class Square looks like.
- Sometimes you have no idea what class a Base* really is and you need to
- know somehow. The above code is distasteful, but that's why RTTI was
- introduced.
- This technique is preferable to implementing the specific function in
- the base class because there might be several functions you want to call
- in the derived class; once you have a pointer to the derived class you
- can call all its functions.
-
- David White
- davidw@werple.mira.net.au
-